<?php
session_start();

if (!isset($_SESSION['username'])) {
    header('Location: login.php');
    exit();
}

require_once 'track_online.php';

$currentUser = $_SESSION['username'];
$groupId = $_GET['group_id'] ?? null;
$targetUser = $_GET['user'] ?? null;

// 禁言配置文件
$muteFile = __DIR__ . "/ql/jy.json";
$muteData = file_exists($muteFile) ? json_decode(file_get_contents($muteFile), true) : [];

// 处理禁言请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? null;
    $groupId = $_POST['group_id'] ?? null;
    $targetUser = $_POST['user'] ?? null;
    $duration = $_POST['duration'] ?? 0;
    $reason = $_POST['reason'] ?? '违反群规';
    
    if (!$groupId || !$targetUser) {
        echo json_encode(['status' => 'error', 'message' => '参数错误']);
        exit();
    }
    
    // 初始化群组禁言数据
    if (!isset($muteData[$groupId])) {
        $muteData[$groupId] = [];
    }
    
    if ($action === 'mute') {
        // 计算禁言结束时间
        $endTime = time() + ($duration * 60); // 分钟转换为秒
        
        $muteData[$groupId][$targetUser] = [
            'end_time' => $endTime,
            'reason' => $reason,
            'muted_by' => $currentUser,
            'muted_at' => time()
        ];
        
        file_put_contents($muteFile, json_encode($muteData));
        echo json_encode(['status' => 'success', 'message' => '用户已禁言']);
        exit();
    }
    
    if ($action === 'unmute') {
        if (isset($muteData[$groupId][$targetUser])) {
            unset($muteData[$groupId][$targetUser]);
            file_put_contents($muteFile, json_encode($muteData));
            echo json_encode(['status' => 'success', 'message' => '用户已解禁']);
            exit();
        }
        
        echo json_encode(['status' => 'error', 'message' => '用户未被禁言']);
        exit();
    }
}

// 获取群组禁言列表
if ($groupId && $_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['get_muted_users'])) {
    $mutedUsers = $muteData[$groupId] ?? [];
    
    // 添加用户名和剩余时间
    foreach ($mutedUsers as $username => $muteInfo) {
        $mutedUsers[$username]['username'] = $username;
        $mutedUsers[$username]['time_left'] = max(0, $muteInfo['end_time'] - time());
    }
    
    echo json_encode(array_values($mutedUsers));
    exit();
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>禁言管理</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* 样式代码（根据实际需要添加） */
    </style>
</head>
<body>
    <!-- 禁言管理界面 -->
</body>
</html>